// 向后台发送消息
chrome.runtime.sendMessage({ greeting: '你好，我是content-script呀，我主动发消息给后台！' }, function (response) {
  console.log('收到来自后台的回复：' + response);
});
window.addEventListener("message", function (e) {
  console.log(e.data);
}, false);


// 监听长连接chrome.tabs.sendMessage
chrome.runtime.onConnect.addListener(function (port) {
  console.log(port);
  if (port.name == 'test-connect') {
    port.onMessage.addListener(function (msg) {
      console.log('收到长连接消息：', msg);

      switch (msg.type) {
        case 'get-cookie':
          getCurrentTabCookie((message) => {
            port.postMessage({ type: 'save-cookie', data: message });
          });

          break;
        case 'set-cookie':
          setCookieToCurrentPage(msg.data);
          port.postMessage({ type: 'msg', data: "cookie storage 信息已经注入到当前页面" });
          break;
        default:
          console.log("content-script 收到消息:", msg)
      }
    });
  }
});


/**
 * 注入其他域名的cookie，storage等信息到当前页面
 * @param {*} data
 */
var setCookieToCurrentPage = function (data) {
  // 1. 设置localStorage
  Object.keys(data.storage).forEach(key => {
    localStorage.setItem(key, data.storage[key])
  })
  // 2. 设置sessionStorage
  Object.keys(data.session).forEach(key => {
    sessionStorage.setItem(key, data.session[key])
  })
  // 3. 设置cookie

  document.cookie = data.cookie;
}
/**
 * 获取
 */
var getCurrentTabCookie = function (callback) {
  // 获取当前登录信息，准备注入
  var host = location.host;
  var cookie = document.cookie;
  var storage = localStorage;
  var session = sessionStorage;


  var postMsg = {
    host, cookie, storage, session
  }
  console.log(">>> content-script 组装到登录信息：", postMsg)
  callback(postMsg);

}
